package service

import (
	"fileNest/dao"
	"fileNest/global"
	"fileNest/model"
	"fileNest/storage"
	"fmt"
	"mime/multipart"
	"time"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
)

func UploadFile(ctx *gin.Context, userID string, parentID *primitive.ObjectID, fileHeader *multipart.FileHeader) (err error) {
	filename := fileHeader.Filename
	size := uint64(fileHeader.Size)
	mimeType := fileHeader.Header.Get("Content-Type")

	// 拼接文件储存路劲&minio储存名称
	var storagePath string
	if parentID != nil {
		storagePath = fmt.Sprintf("%s/%s/%s", userID, parentID.Hex(), filename)
	} else {
		storagePath = fmt.Sprintf("%s/%s", userID, filename)
	}

	now := time.Now()
	id := primitive.NewObjectID()
	entry := model.FileEntry{
		ID:          &id,
		UserID:      userID,
		ParentID:    parentID,
		Name:        filename,
		Size:        size,
		MimeType:    mimeType,
		IsDir:       false,
		StoragePath: storagePath,
		CreatedAt:   &now,
	}

	var entries = bson.M{
		"user_id":   userID,
		"parent_id": parentID,
		"name":      filename,
	}

	if err = dao.DBFindOne("entries", entries, &entries); err == nil {
		err = fmt.Errorf("该目录下已存在名为 \"%s\" 的文件，请检查文件夹或回收站", filename)
		return
	} else if err != mongo.ErrNoDocuments {
		// 查找时出现数据库错误
		return
	}

	if err = storage.AddMinioFile(global.BucketName, fileHeader, storagePath); err != nil {
		return
	}
	if _, err = dao.DBAdd("entries", entry); err != nil {
		return
	}
	return
}
